import pygame
import random


def gen_points(num):
    for i in range(num):
        points.append([random.randint(20, 380), -120*i+30])
# pygame的初始化
pygame.init()
# 设置屏幕大小
screen = pygame.display.set_mode((400, 600))

rect = pygame.Rect(200, 500, 100, 20)
# 用于判断是否循环的变量
is_loop = True
# 分数
score = 0
# 命数
life = 3
# sudu
speed = 10
# 小球的坐标
points = []
gen_points(100)
# 时钟
clock = pygame.time.Clock()
# 设置字体字号
font = pygame.font.SysFont(None, 40)
while is_loop:
    # 事件的监听
    for event in pygame.event.get():
        # 点击退出退出游戏
        if event.type == pygame.QUIT:
            is_loop=False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                if rect.x >0:
                    rect.x -= 30
            elif event.key == pygame.K_RIGHT:
                if rect.x+rect.w <= 400:
                    rect.x +=30

    # 屏幕填充黑色
    screen.fill((0,0,0))
    # 向screen上画一个矩形
    pygame.draw.rect(screen, (255, 0,0), rect)
    for point in points:
        # 向screen上画一个圆形
        pygame.draw.circle(screen, (0, 255,0),point, 20)
    # 通过font渲染文字
    score_text = font.render(f"Score:{score}",True, (255,255,255))
    # 将文字放到屏幕对应的位置上
    screen.blit(score_text, (5,5))
    # 通过font渲染文字
    life_text = font.render(f"life:{life}", True, (255, 255, 255))
    # 将文字放到屏幕对应的位置上
    screen.blit(life_text, (320, 5))
    for c_pos in points:
        if c_pos[1] > 470:
            if rect.x<c_pos[0] < rect.x+rect.w:
                score +=1
                c_pos[1] = -400
                c_pos[0] = random.randint(20, 380)
            if c_pos[1]> 600:
                life-=1
                c_pos[1] = -400
                c_pos[0] = random.randint(20, 380)
            # 改变小球坐标

        c_pos[1]+=speed
    if score%8 ==0:
        speed+=2

    # pygame进行更新
    pygame.display.update()
    # 每秒不超过20帧
    clock.tick(20)

# 退出
pygame.quit()